package top.yueyazhui.kaptcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class CaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/img1")
    public void getCaptchaImg(HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String text = defaultKaptcha.createText();
        // 生成验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @GetMapping("/session")
    public void getCaptchaSession(HttpSession session) {
        String kaptchaCode = (String) session.getAttribute("kaptchaCode");
        System.out.println("kaptchaCode = " + kaptchaCode);
    }
}
